from DataAccess.blp_client import *

from datetime import date, timedelta

def query_blp_static(tick_list, field_list):

	r = query_blp_data(tick_list, field_list)

	data = {}
	
	for tick in tick_list:
		data[tick] = {}
		
		for field in field_list:
			data[tick][field] = 'NA'
			
			if r.has_key(tick) and r[tick].has_key(field):
				data[tick][field] = r[tick][field]

	return data
	
def query_blp_latest(tick_list, field_list, ref_date):

	start_date = ref_date - timedelta(days=120)
	r = query_blp_data(tick_list, field_list, start_date, ref_date)
	
	data = {}
	
	for tick in tick_list:
		data[tick] = {}
		
		for field in field_list:
			data[tick][field] = 'NA'
			
			d = ref_date
			loop = True
			while (d >= start_date) and loop:
				if r.has_key(tick) and r[tick].has_key(d.isoformat()) and r[tick][d.isoformat()].has_key(field):
					data[tick][field] = r[tick][d.isoformat()][field]
					loop = False
				else:
					d -= timedelta(days=1)
	return data
	
def query_blp_average(tick_list, field_list, start_date, end_date):

	r = query_blp_data(tick_list, field_list, start_date, end_date)
	
	data = {}
	
	for tick in tick_list:
		data[tick] = {}
		
		for field in field_list:
			data[tick][field] = 'NA'
			
			if r.has_key(tick):
				values = [v[field] for v in r[tick].values() if (isinstance(v, dict) and v.has_key(field))]
				
				if len(values) > 0:
					data[tick][field] = sum(values) / len(values)
			
	return data
		
		
		
		
		